package es.juanc.load.recursos;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Properties;

public class PropertyLoaderTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		try {
			
			// - FileInputStream: ruta completa
			File file = new File( "config.properties" );
			FileInputStream fis = new FileInputStream( file );
			
			Properties prop = new Properties();
			prop.load( fis );
			fis.close();
			
			printProps( prop );
			//System.out.println( prop.getProperty( "una.propiedad" ) + ", " + prop.getProperty( "dos.propiedad" ) );
			
			// - getResourceAsStream: ruta en classpath
			InputStream is = PropertyLoaderTest.class.getResourceAsStream( "/config-cp.properties" );
			prop.load( is );
			is.close();

			System.out.println();
			printProps( prop );
			//System.out.println( prop.getProperty( "una.propiedad" ) + ", " + prop.getProperty( "dos.propiedad" ) );
			
			ClassLoader loader;
			// - Thread.currentThread().getContextClassLoader(): ruta en classpath => sin /
			loader = Thread.currentThread().getContextClassLoader();
			System.out.println();
			print( loader.getResourceAsStream("config-cp.properties") );
			
			// - ClassLoader.getSystemClassLoader(): ruta en classpath => sin /
			loader = ClassLoader.getSystemClassLoader();
			System.out.println();
			print( loader.getResourceAsStream("config-cp.properties") );
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void printProps( Properties prop ) throws IOException {
		for( Enumeration keys = prop.keys() ; keys.hasMoreElements() ; ) {
			final String key = (String) keys.nextElement();
			final String value = prop.getProperty(key);
			System.out.println( key + " = " + value );
		}
	}
	
	public static void print( InputStream is ) throws IOException {
		BufferedReader br = new BufferedReader( new InputStreamReader( is ) );
	    String line;
	    while( (line = br.readLine()) != null ) {
	    	System.out.println( line );
	    }
	    br.close();
	}
}